package com.apkcore.core.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.provider.Settings
import android.text.format.Formatter
import com.apkcore.core.cp.ApkcoreContentProvider
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.Enumeration

object Utils {
    fun getRootPath(context: Context, dataP: Boolean = false): String {
        val path = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q || dataP) {
            //         /storage/emulated/0/Android/data/包名/files
            val externalFileDir = context.getExternalFilesDir(null)
            externalFileDir!!.absolutePath
        } else {
            Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return path
    }

    private var serial = ""

    @SuppressLint("HardwareIds")
    fun getSerial(): String {
        if (serial.isNotEmpty()) {
            return serial
        }
        serial = try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Build.getSerial()
            } else {
                Build.SERIAL
            }
        } catch (e: Exception) {
            Settings.System.getString(
                ApkcoreContentProvider.appContext.contentResolver,
                Settings.Secure.ANDROID_ID
            )
        }
        return serial
    }

    fun getDeviceIpAddress(): String? {
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            // Android 9 (Pie) 及以下版本使用 WifiManager 获取 IP 地址
            getWifiIpAddress(ApkcoreContentProvider.appContext)
        } else {
            // Android 10 及以上版本使用 NetworkInterface 获取 IP 地址
            getNetworkInterfaceIpAddress()
        }
    }

    private fun getWifiIpAddress(context: Context): String? {
        val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo
        return Formatter.formatIpAddress(wifiInfo.ipAddress)
    }

    private fun getNetworkInterfaceIpAddress(): String? {
        try {
            val interfaces: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
            for (networkInterface in interfaces) {
                val inetAddresses: Enumeration<InetAddress> = networkInterface.inetAddresses
                for (inetAddress in inetAddresses) {
                    // 过滤掉回环地址和链路本地地址，并且只返回 IPv4 地址
                    if (!inetAddress.isLoopbackAddress && inetAddress.isSiteLocalAddress && inetAddress is InetAddress) {
                        return inetAddress.hostAddress
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun getResolution(): Pair<Int, Int> {
        val displayMetrics = Resources.getSystem().displayMetrics
        val width = displayMetrics.widthPixels
        val height = displayMetrics.heightPixels
        return Pair(width, height)
    }

    private fun getStorageInfo(path: String): Triple<String, String, String> {
        val statFs = StatFs(path)
        val blockSize = statFs.blockSizeLong
        val totalBlocks = statFs.blockCountLong
        val availableBlocks = statFs.availableBlocksLong

        val totalSize = totalBlocks * blockSize
        val availableSize = availableBlocks * blockSize
        val usedSize = totalSize - availableSize

        return Triple(formatSize(totalSize), formatSize(availableSize), formatSize(usedSize))
    }

    private fun formatSize(size: Long): String {
        val kb = 1024
        val mb = kb * 1024
        val gb = mb * 1024

        return when {
            size >= gb -> String.format("%.1f GB", size.toFloat() / gb)
            size >= mb -> String.format("%.1f MB", size.toFloat() / mb)
            size >= kb -> String.format("%.1f KB", size.toFloat() / kb)
            else -> String.format("%d B", size)
        }
    }

    fun getInternalStorageInfo(): Triple<String, String, String> {
        return getStorageInfo(Environment.getDataDirectory().path)
    }

    fun getExternalStorageInfo(): Triple<String, String, String>? {
        val externalStorageDirectory = Environment.getExternalStorageDirectory()
        return externalStorageDirectory?.let { getStorageInfo(it.path) }
    }

}
